const React = require('react');
const {
  View,
  StyleSheet,
  FlatList
} = require('react-native');
const {
  JDScrollView,
  JDText,
  JDRouter,
  JDButton,
  JDTouchable,
} = require('@areslabs/jdreact-core-lib');
const { NavigationBar } = JDRouter;


function getMockData() {
  let result = [];
  for (let i = 0; i < 100; i++) {
    result.push({
      id: i,
      title: `Hello ${parseInt(Math.random() * 10000)}`
    });
  }
  return result;
}

class PullFlatList extends React.Component {
  state = {
    isRefreshing: false,
    listData: getMockData(),
  };

  render() {
    return (
      <View style={styles.wrapper}>
        <NavigationBar Title="FlatList" />
        <FlatList
          ref="flatList"
          style={styles.wrapper}
          contentContainerStyle={styles.contentContainerStyle}
          data={this.state.listData}
          renderItem={this._renderRow}
          keyExtractor={this._keyExtractor}
          refreshing={this.state.isRefreshing}
          onRefresh={() => { this.onRefresh(); }}
          onScroll={this._onScroll}
          renderHeader={this._renderHeader}
          renderScrollComponent={(props) => (<JDScrollView {...props} renderHeader={this._renderHeader}/>)}
        />
      </View>
    );
  }

  _renderHeader = (refreshStatus) => {
    var status = "";
    switch (refreshStatus)
    {
      case 'pullToRefresh':
      status = '下拉刷新';
      break;
      case 'releaseToRefresh':
      status = '松手更新';
      break;
      case 'refreshing':
      status = '刷新中。。。。';
      break;
    }
    return <View style={{height: 75, alignItems: 'center', justifyContent: 'center'}}><JDText>{status} </JDText></View>

  };

  _onScroll = (e) => {
    console.log(e.nativeEvent.contentOffset.y)

    console.log(`JDScrollView.bodySize:${JDScrollView.bodySize}`)
    console.log(`JDScrollView.maxSize:${JDScrollView.maxSize}`)
  };

  _keyExtractor = (item, index) => {
    return String(item.id)
  };

  _renderRow = ({ item, index }) => {
    if (index === 20) {
      return (
        <JDTouchable contentContainerStyle={styles.row} onPress={() => { 
          this.refs.flatList.scrollToOffset({offset:0})
         }}>
          <JDText>{'点击回到顶部'}</JDText>
        </JDTouchable>
      )
    }
    return (
      <JDTouchable contentContainerStyle={styles.row} onPress={() => { alert(item.title); }}>
        <JDText>{item.title}</JDText>
      </JDTouchable>
    );
  };

  onRefresh = () => {
    this.setState({
      isRefreshing: true,
    });
    setTimeout(() => {
      this.setState({
        isRefreshing: false,
        listData: getMockData()
      });
    }, 3000);
  };
}

const styles = StyleSheet.create({
  wrapper: {
    flex: 1,
  },
  contentContainerStyle: {
    backgroundColor: 'rgba(0, 0, 0, 0.1)',
  },
  row: {
    height: 100,
    borderColor: '#F00',
    borderWidth: 1,
    marginVertical: 10,
  }
});

module.exports = PullFlatList;
